package com.wowangz.cms.topic.news.api;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;

import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.wowangz.cms.common.mongo.MongoDBManager;
import com.wowangz.cms.syscore.api.BaseController;
import com.wowangz.cms.syscore.utils.ServletUtils;

@Controller
@Scope("prototype")
public class FileUploadController extends BaseController {

	@RequestMapping(value = "ckediter/uploadImageFile.web", method = { RequestMethod.GET, RequestMethod.POST })
	public void uploadImageFile(MultipartHttpServletRequest request, Model model, HttpServletResponse response) {
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		try {
			Iterator<String> iter = request.getFileNames();
			if(iter.hasNext()){
				while (iter.hasNext()) {
					MultipartFile multipartFile = request.getFile(iter.next());
					InputStream inputStream = multipartFile.getInputStream();
					MongoDBManager manager = MongoDBManager.getDefaultMongoDBManager();
					String fileName = ServletUtils.uploadMongodbfile(inputStream, manager,manager.getPictureDBName());
					String accessUrl = manager.getAccessUrl();
					System.out.println(accessUrl + "/" + fileName);
					String callback = request.getParameter("CKEditorFuncNum");
					out.println("<script type=\"text/javascript\">");
					out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ", '" + (accessUrl + "/" + fileName) + "','');");
					out.println("</script>");
				}
			} else {
				out.println("<script type=\"text/javascript\">");
				out.println("alert('file is not exsit')");
				out.println("</script>");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			String callback = request.getParameter("CKEditorFuncNum");
			out.println("<script type=\"text/javascript\">");
			out.print("alert('*文件大于2M，超过系统文件上传限制');");
			out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ", '','');");
			out.println("</script>");
		}
	}

}
